import React, { useCallback, useEffect, useState } from 'react';
import style from './index.module.scss';
import Button from 'antd/es/button';
import 'antd/es/button/style/css';
import { AppStore } from '../../store';
import { Form, IFormChildren } from '../../components/form';
import { slave } from '../../slave';
import {
  GenerateService,
  IParamModelLiteData,
  ISelectParamForm,
  SelectParamService,
  ToastService,
} from '@manycore/pages-vm-api';
import Image from 'antd/es/image';
import 'antd/es/image/style/css';

const updateSelectedParams = async (param: IParamModelLiteData) => {
  const service = slave.getService(SelectParamService)!;
  await service.updateParameters({
    fields: [param],
  });
};

export function AppForm() {
  const { appState, updateGeneratingState, updateEditFormState, updateGenerateFormState } = AppStore.useContainer();
  const hardwareModel = appState.modeOption?.hardwareModel;
  const form = hardwareModel === 'add' ? appState.generateForm : appState.editForm;
  const [formData, updateFormData] = useState<Array<ISelectParamForm | IFormChildren>>(form);

  useEffect(() => {
    const currentState: Array<ISelectParamForm | IFormChildren> = [
      ...(hardwareModel === 'add' ? appState.generateForm : appState.editForm),
    ];
    if (appState.sketchImageUrl && hardwareModel === 'edit') {
      currentState.push({
        groupName: '标注图参考',
        children: <Image width={240} className={style.imageRoot} src={appState.sketchImageUrl} preview={false} />,
      });
    }
    updateFormData(currentState);
  }, [hardwareModel, appState.sketchImageUrl, appState.generateForm, appState.editForm]);

  const generateCallback = useCallback(
    function () {
      const service = slave.getService(GenerateService)!;
      const toast = slave.getService(ToastService)!;
      updateGeneratingState(true);
      toast.info('正在生成掩门五金');
      service
        .generate({
          form: appState.generateForm,
        })
        .then(() => {
          return toast.info('掩门五金生成成功');
        })
        .catch((e) => {
          console.log(e);
          return toast.error('掩门五金生成失败');
        })
        .finally(() => {
          updateGeneratingState(false);
        });
    },
    [appState.generateForm]
  );

  const onFormFieldChanged = useCallback(
    (field: IParamModelLiteData, value) => {
      const formClone = [...form];
      let i = -1;
      while (i++ < formClone.length) {
        const current = formClone[i];
        const index = current.fields.indexOf(field);
        if (index !== -1) {
          const currentField = [...current.fields];
          currentField.splice(index, 1, {
            ...field,
            value,
          });
          formClone[i] = {
            ...current,
            fields: currentField,
          };
          break;
        }
      }
      if (hardwareModel === 'add') {
        updateGenerateFormState(formClone);
      } else {
        // 更新页面中的状态
        updateEditFormState(formClone);
        // 更新选中的模型
        updateSelectedParams({
          ...field,
          value,
        }).then(() => {
          return slave.getService(SelectParamService)!.getParameters().then(updateEditFormState);
        });
      }
    },
    [formData, hardwareModel]
  );

  return (
    <div className={style.appFormLayout}>
      <div className={style.appFormRoot}>
        <Form form={formData} onChange={onFormFieldChanged} />
      </div>
      {
        /* 仅添加五金时，才展示生成按钮 */
        hardwareModel === 'add' && appState.hasSelected && (
          <div className={style.appFormBottomBar}>
            <Button disabled={appState.generating} onClick={generateCallback} size="middle" type="primary">
              生成
            </Button>
          </div>
        )
      }
    </div>
  );
}
